$(function(){
    message = getQueryString('message');

    if (message) {
        alert(message);
        location.href = location.origin + location.pathname;
    }

    /** index **/
    $('.media-list .latestComments').click(function(){
        location.pathname = '/images/'+$(this).data('id');
    })

    $('#login-btn').click(function(){
        $('#login-error').text('')
        $.post('/users/login',
            {
                username:$('#login-form input[name="username"]').val(),
                password:$('#login-form input[name="password"]').val()
            }
            ,function(resp){
                if (resp.success) {
                    alert('登陆成功')
                    location.reload();
                }else{
                    $('#login-error').text('用户名或密码错误!')
                }
            }
        )
    })

    $('#toregister').click(function(){
        $('#register-error').text('');
        var username = $('#reg-form input[name="username"]').val();
        var email = $('#reg-form input[name="email"]').val();
        var password = $('#reg-form input[name="password"]').val();
        if($('#reg-form input[name="username"]').closest('div.form-group').hasClass('has-error')){
            $('#register-error').text('密码长度必须大于5')
            return ;
        }
        if($('#reg-form input[name="email"]').closest('div.form-group').hasClass('has-error')){
            $('#register-error').text('邮箱格式存在问题！')
            return ;
        }
        if($('#reg-form input[name="password"]').closest('div.form-group').hasClass('has-error')){
            $('#register-error').text('密码长度必须大于5')
            return ;
        }
        $.post('/users/register',
            {username:username,email:email,password:password},
            function(resp){
                if(resp.success){
                    alert('注册成功');
                    location.reload();
                }else {
                    alert('注册失败');
                }
            })
    })

    //状态重置
    $('#reg-form input').on('focus',function(){
        $(this).closest('div.form-group').removeClass('has-success').removeClass('has-error');
        $('#register-error').text('');
    })

    //用户名检查
    $('#reg-form input[name="username"]').on('blur',function(){
        var parent = $(this).closest('div.form-group');
        var username = $(this).val();
        if(!/.{5,}/.test(username)){
            $('#register-error').text('用户名长度必须大于5');
            $(parent).addClass('has-error');
            return ;
        }
        fetch('users/check?username='+username,{method:'GET'})
        .then(function(resp){
            return resp.json();
        })
        .then(function(res){
            if(res.exist){
                $('#register-error').text('用户名已经存在！')
                $(parent).addClass('has-error');
            }else{
                $(parent).addClass('has-success');
            }
            console.log(res);
        })
        .catch(function(err){
            console.log(err);
        })
    })


    // 邮箱检查
    $('#reg-form input[name="email"]').on('blur',function(){
        var parent = $(this).closest('div.form-group');
        var email = $(this).val();
        if(!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)){
            $('#register-error').text('邮箱格式存在问题！');
            $(parent).addClass('has-error');
        }else {
            $(parent).addClass('has-success');
        }
    })

    // 密码检查
    $('#reg-form input[name="password"]').on('blur',function(){
        var parent = $(this).closest('div.form-group');
        var password = $(this).val();
        if(password.length<=5){
            $('#register-error').text('密码长度必须大于5');
            $(parent).addClass('has-error');
        }else {
            $(parent).addClass('has-success');
        }
    })


    /** image **/
    //like
    $('#btn-like').click(function(){
        // var id = $(this).data('id');
        // $.post('/images/'+ id+'/like',function(data){
        //     $('.likes-count').text(data.likes);
        // })

        var self = this;
        fetch('/images/'+ $(self).data('id')+'/like',{method:'POST'})
        .then(function(resp){
            return resp.json();
        }).
        then(function(res){
            $('.likes-count').text(res.likes);
        })
        .catch(function(err){
            console.log(err);
        })
    });

    //delete image
    //$('#myconfirm').hide()
    $('#btn-delete').click(function(){
        $('#myconfirm').fadeIn()
    })
    $('#myconfirm .deleteNo').click(function(){
        $('#myconfirm').fadeOut()
    })
    $('#myconfirm .deleteYes').click(function(){
        fetch('/images/' + $('#btn-delete').data('id'),{method:'DELETE'})
        .then(function(resp){
            return resp.json()
        })
        .then(function(obj){
            if(obj.ok && obj.ok ===1 ){
                $('#btn-delete').empty().text('已删除！')
                .removeClass('btn-danger').addClass('btn-success')
                .attr('disabled',true)
                $('#btn-like').attr('disabled',true)
                $('#comment-btn').attr('disabled',true)
                $('.this-image-comments').empty()
                $('.this-image-comments').text('已删除！3秒后自动跳转回主页')
                setTimeout(function(){location.href = location.origin},3000);
            }else{
                alert('请求失败' + JSON.stringify(obj))
            }
        }).
        catch(function(err){
            alert('网络错误！')
        })
        $('#myconfirm').fadeOut()
    })

    //comment
    $('#post-comment').hide();
    $('#btn-comment').click(function(){
        $('#post-comment').slideDown();
    })
    $('#comment-btn').click(function(e){
        e.preventDefault();
        $('#form-helper').text('');

        var self = $(this);
        var name = $('#post-comment input[name="name"]').val();
        var email = $('#post-comment input[name="email"]').val();
        var comment = $('#post-comment textarea[name="comment"]').val();

        if(!/.+/.test(name)){
            $('#form-helper').text('用户名长度必须大于1');
            return ;
        }else if(!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)){
            $('#form-helper').text('邮箱格式存在问题！');
            return ;
        }else if(comment.length<=5){
            $('#form-helper').text('评论长度必须大于5');
            return ;
        }

        $(self).attr('disabled',true)

        var id = $(this).data('id');
        $.post('/images/'+ id +'/comment/',{
            name:$('#post-comment input[name="name"]').val(),
            email:$('#post-comment input[name="email"]').val(),
            comment:$('#post-comment textarea[name="comment"]').val()
        },function(resp){
            $.get('/images/'+ id +'/comment/',function(comments){
                $('.this-image-comments').empty()
                $('.this-image-comments').hide()
                for(let i = 0;i < comments.length;i++){
                    console.log(comments[i]);
                    $('.this-image-comments').append(commentModels(comments[i]))
                }
                $('.this-image-comments').fadeIn(1000)
                formReset();
            })
        });
    })

})

//comment form reset
function formReset(){
    $('#post-comment input[name="name"]').val('');
    $('#post-comment input[name="email"]').val('');
    $('#post-comment textarea[name="comment"]').val('');
    $('#comment-btn').attr('disabled',false);
}

timeago = function(timestamp){
    moment.updateLocale('zh-cn')
    return moment(timestamp).startOf('minute').fromNow();
}

function commentModels(data){
    return '<li class="media">'+
                '<a class="pull-left" href="#"><img class="media-object img-circle" src="http://www.gravatar.com/avatar/?d=monsterid&amp;s=45"></a>'+
                '<div class="media-body">'+
                    '<strong class="media-heading">'+data.name+'</strong>&nbsp;'+
                    '<small class="text-muted">'+timeago(data.timestamp)+'</small>'+
                    '<p>'+data.comment+'</p>'+
                '</div>'+
            '</li>'
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
